import './assets/main.css'
import 'vant/lib/index.css'

import { createApp } from 'vue'
import App from './App.vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import config from './config'

// 引入 Vant 组件
import { Popup, List, Cell, Button, Form, Field, Picker, Toast, Dialog, RadioGroup, Radio, showSuccessToast, showFailToast, Popover } from 'vant'

// 页面组件
import Home from './pages/Home.vue'
import AccountDetail from './pages/AccountDetail.vue'
import RecordEdit from './pages/RecordEdit.vue'
import Login from './pages/Login.vue'
import UserStatus from './pages/UserStatus.vue'
import UserAccountDetail from './pages/UserAccountDetail.vue'
import ResetPassword from './pages/ResetPassword.vue'

// 打印当前环境和API基础URL
console.log(`当前环境: ${config.env}, API基础URL: ${config.baseUrl}`)

// 路由配置
const routes = [
  { 
    path: '/', 
    component: Home,
    meta: { requiresAuth: true }
  },
  { 
    path: '/account/:id', 
    component: AccountDetail,
    meta: { requiresAuth: true }
  },
  { 
    path: '/record/edit/:id?', 
    component: RecordEdit,
    meta: { requiresAuth: true }
  },
  { 
    path: '/login', 
    component: Login,
    meta: { guest: true }
  },
  { 
    path: '/user/:userId/status', 
    component: UserStatus,
    meta: { requiresAuth: false }
  },
  { 
    path: '/user/:userId/account/:accountId', 
    component: UserAccountDetail,
    meta: { requiresAuth: false }
  },
  {
    path: '/reset-password',
    component: ResetPassword,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = !!localStorage.getItem('token')
  
  // 用户状态页面不需要登录
  if (to.path.includes('/user/') && (to.path.includes('/status') || to.path.includes('/account/'))) {
    next()
    return
  }
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要登录的页面
    if (!isLoggedIn) {
      next('/login')
    } else {
      next()
    }
  } else if (to.matched.some(record => record.meta.guest)) {
    // 游客页面（如登录页）
    if (isLoggedIn) {
      next('/')
    } else {
      next()
    }
  } else {
    next()
  }
})

const app = createApp(App)
app.use(router)
app.use(Popup)
app.use(List)
app.use(Cell)
app.use(Button)
app.use(Form)
app.use(Field)
app.use(Picker)
app.use(Toast)
app.use(Dialog)
app.use(RadioGroup)
app.use(Radio)
app.use(Popover)

app.mount('#app')
